package com.peas.platform.module.icims.contract.initial.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.peas.platform.common.core.annotation.Aop;
import com.peas.platform.common.core.dto.ResponseDto;
import com.peas.platform.module.icims.contract.initial.dto.ContractInitialBorrowDto;
import com.peas.platform.module.icims.contract.initial.dto.ContractInitialDto;
import com.peas.platform.module.icims.contract.initial.service.ContractInitialBorrowService;
import com.peas.platform.module.icims.contract.initial.service.ContractInitialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Api(tags = "自定义接口-[合同管理]初始合同借阅")
@RestController
@RequestMapping("/api/v1/customContractInitialBorrow")
@Slf4j
public class CustomContractInitialBorrowController {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    @Resource
    private ContractInitialBorrowService contractInitialBorrowService;
    @Resource
    private ContractInitialService contractInitialService;

    @SneakyThrows
    @ApiOperation(value = "下载合同借阅")
    @GetMapping(value = "/downloadContractInitialBorrow/{contractInitialBorrowId}")
    @Aop(enabled = false)
    public void downloadContractInitialBorrow(@PathVariable(value = "contractInitialBorrowId") Long contractInitialBorrowId) {
        try {
            assert request != null;
            ContractInitialBorrowDto dto = contractInitialBorrowService.getById(contractInitialBorrowId);
            Assert.notNull(dto, "找不到合同借阅记录");
            ContractInitialDto contract = contractInitialService.getById(dto.getContractInitialId());
            Assert.notNull(contract, "找不到合同");
            String fileName = "合同下载_" + contract.getCode() + "_" + DateUtil.today() + ".doc";
            String name = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            //word内容
            dto.setDownloadTimes(dto.getDownloadTimes() + 1);
            contractInitialBorrowService.updateById(dto);
            String html = contract.getContent();
            byte[] bs = html.getBytes(StandardCharsets.UTF_8);  //这里是必须要设置编码的，不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(bs);//将字节数组包装到流中
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            directory.createDocument("WordDocument", bais);
            //输出文件
            response.setHeader("Content-disposition", "attachment; filename=" + name);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            //response.setContentType("application/msword;charset=utf-8");//导出word格式
            response.setContentType("application/octet-stream;charset=utf-8");//导出word格式
            OutputStream os = response.getOutputStream();
            poifs.writeFilesystem(os);
            bais.close();
            os.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setContentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8).toString());
            throw e;
        }
    }

    @ApiOperation(value = "归还合同借阅")
    @PostMapping(value = "/returnContractInitialBorrow/{contractInitialBorrowId}")
    public ResponseDto<Boolean> returnContractInitialBorrow(@PathVariable(value = "contractInitialBorrowId") Long contractInitialBorrowId) {
        contractInitialBorrowService.returnContractInitialBorrow(contractInitialBorrowId);
        return ResponseDto.getSuccessResponseDto(true);
    }

}
